/**
 * @Description: webpack配置
 * @Author 卞鹏飞 <228443632@qq.com>
 * @create 2023/3/26 20:54
 * @example
 * 打包
 */
const path2 = require('path')
const pkg = require('./package.json')
const { env, envMapEncode, envEncode, proxyEncode } = require('./env')
const { IS_PRO, dynamicLoadEnvVars } = require('./scripts/utils')
const WindiCSSWebpackPlugin = require('windicss-webpack-plugin')
const webpack = require('webpack')

const port = 7089
const ROOT_PATH = path2.resolve(__dirname)
const SRC_PATH = path2.join(ROOT_PATH, 'src')

const lintOnSave = false // 是否开启eslint
const publicPath = './'

module.exports = {
  publicPath,
  lintOnSave,
  // transpileDependencies: true,
  css: {
    extract: {
      ignoreOrder: true
    },
    loaderOptions: {
      scss: {
        // @/ 是 src/ 的别名
        // 所以这里假设你有 `src/variables.sass` 这个文件
        // 注意：在 sass-loader v8 中，这个选项名是 "prependData"
        // additionalData: '@use "~@/style/el-plus.scss" as *;'
        additionalData: '@use "~@/style/elementPlus/index.scss" as *;'
      }
    }
  },
  // 第三方插件配置
  pluginOptions: {
    'style-resources-loader': {
      preProcessor: 'less',
      patterns: [
        path2.join(SRC_PATH, 'style/app/variables.less'),
        path2.join(SRC_PATH, 'style/app/mixin.less'),
        path2.join(SRC_PATH, 'style/app/transition.less')
      ]
    }
  },
  chainWebpack: (config) => {
    // dll.chainWebpack(config)

    config.plugin('definePlugin').use(webpack.DefinePlugin, [
      {
        PUBLIC_URL: JSON.stringify(String(publicPath)),
        'process.env.APP_MODE': JSON.stringify(process.env.APP_MODE),
        'process.env.ENV': JSON.stringify(envEncode),
        'process.env.ENV_MAP': JSON.stringify(envMapEncode),
        'process.env.ENV_PROXY': JSON.stringify(proxyEncode),
        'process.env.PUBLIC_URL': JSON.stringify(String(publicPath)) // 所有加载js文件动态前缀
      }
    ])

    if (IS_PRO) {
      //
    } else {
      // 开发环境
      config.optimization.splitChunks({
        chunks: 'all'
      })
    }

    config.plugin('html').tap((args) => {
      return args
    })

    config.module
      .rule('js')
      .exclude.add(path2.join(ROOT_PATH, 'node_module'))
      .end()
      .rule('rule-mjs2')
      .test(/\.mjs$/)
      .include.add(/node_modules/)
      .end()
      .type('javascript/auto')

    config.resolve.alias
      .set('@root', ROOT_PATH)
      .set('@', path2.join(ROOT_PATH, 'src'))
      .set('~@', path2.join(ROOT_PATH, 'src'))
      .set('@store', path2.join(ROOT_PATH, 'src/store'))

    config.plugin('WindiCSSWebpackPlugin').use(WindiCSSWebpackPlugin)

    if (IS_PRO) {
    } else {
      // 开发环境
      config.output.hashFunction(`xxhash64`)
      config.devtool('eval-cheap-module-source-map')
    }
  },
  configureWebpack() {
    const devServer = {
      proxy: Object.values(env.proxy).reduce((pre, cur) => ({ ...pre, [cur['prefix']]: cur['rule'] }), {})
    }
    return {
      target: dynamicLoadEnvVars({ dev: ['web', 'es2022'], prod: 'web' }),
      stats: {
        all: false
        // all: 'errors-only'
      },
      output: {
        chunkLoadingGlobal: `webpackJsonp_${pkg?.name}`,
        clean: true
      },
      resolve: {
        fallback: {
          path: require.resolve('path-browserify'),
          process: require.resolve('process/browser'),
          url: require.resolve('url')
          // vm: require.resolve('vm-browserify'),
          // timers: require.resolve('timers-browserify'),
          // https: require.resolve('https-browserify'),
          // http: require.resolve('stream-http'),
          // stream: require.resolve('stream-browserify'),
          // querystring: require.resolve('querystring-es3'),
        }
      },
      cache: {
        type: 'filesystem', // memory
        store: 'pack',
        allowCollectingMemory: false,
        buildDependencies: {
          config: [__filename]
        },
        maxMemoryGenerations: dynamicLoadEnvVars({ dev: 20, prod: Infinity })
      },
      module: dynamicLoadEnvVars({
        dev: {
          unsafeCache: true
        }
      }),
      experiments: dynamicLoadEnvVars({
        dev: {
          backCompat: false,
          cacheUnaffected: true,
          futureDefaults: false,
          topLevelAwait: true
          // outputModule: true,
          // backCompat: false
          // lazyCompilation: {
          //   entries: true,
          //   imports: true,
          // },
        }
      }),
      devServer: {
        proxy: {
          '/zabbixMenu': {
            target: 'http://150.223.210.158:8081', // 目标服务器地址
            changeOrigin: true,
            pathRewrite: {
              '^/zabbixMenu': '/zabbixMenu'
            }
          }
        },
        port,
        client: {
          overlay: {
            errors: false,
            warnings: false,
            runtimeErrors: false
          },
          progress: false
        },
        compress: true,
        hot: true,
        host: '0.0.0.0',
        open: false,
        headers: {
          'Access-Control-Allow-Origin': '*',
          'Cache-Control': 'private, no-store, no-cache, must-revalidate, proxy-revalidate'
        },
        historyApiFallback: true,
        // ...devServer
      },
      optimization: dynamicLoadEnvVars({
        dev: {
          // splitChunks: false,
          removeAvailableModules: false,
          removeEmptyChunks: false,
          sideEffects: false,
          providedExports: false
        }
      })
      // UnoCSS(),
      // plugins: [UnoCSS(), new webpack.ProgressPlugin({ percentBy: 'entries' })]
      // optimization: {
      //   realContentHash: true
      // }
      // ignoreWarnings: [/only default export is available soon/]
    }
  }
}
